/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server.server;

import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import server.serverDB.ServerDB;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;

/**
 *
 * @author Александр Емельянов (mr.lex91@gmail.com)
 *
 */
public class Server {
    private ServerSocket server;
    private AcceptionHandler accHandler;
    private boolean started=false;
    private ServerDB dataBase;
    private int port;
    private String host;
    private String dbPath;
    public Server(int port, String host, String dbPath) throws IOException
    {
        server=new ServerSocket(port, 0, InetAddress.getByName(host));
        dataBase=new ServerDB(dbPath);
        this.port=port;
        this.host=host;
        this.dbPath=dbPath;
    }
    public void Start()
    {
        if (!started)
        {
            accHandler=new AcceptionHandler(server, dataBase);
            accHandler.Start();
            started=true;
        }
    }
    public void Stop()
    {
        if (started)
        {
            accHandler.Stop();
            accHandler=null;
            started=false;
        }
    }
    public void changeDB(String dbPath)
    {
        if (started)
        {
            Stop();
            dataBase=new ServerDB(dbPath);
            Start();
        }
        else dataBase=new ServerDB(dbPath);
        this.dbPath=dbPath;
    }
    public void changeHOST(String host) throws IOException
    {
        if (started)
        {
            Stop();
            try {
                ServerSocket oldserver=server;
                server=new ServerSocket(port, 0, InetAddress.getByName(host));
                oldserver.close();
            } catch (IOException ex) {
                Start();
                throw new IOException();
            }
            Start();
        }
        else server=new ServerSocket(port, 0, InetAddress.getByName(host));
        this.host=host;
    }
    public void changePORT(int port) throws IOException
    {
        if (started)
        {
            Stop();
            try {
                ServerSocket oldserver=server;
                server=new ServerSocket(port, 0, InetAddress.getByName(host));
                oldserver.close();
            } catch (IOException ex) {
                Start();
                throw new IOException();
            }
            Start();
        }
        else server=new ServerSocket(port, 0, InetAddress.getByName(host));
        this.port=port;
    }
    public void Close() throws IOException
    {
        server.close();
    }
}
